package com.base.cn.platform.os.service.order.init;

import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.ShopType;
import com.base.cn.platform.os.entity.book.Book;
import com.base.cn.platform.os.entity.book.BookCondition;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.CourseCondition;
import com.base.cn.platform.os.entity.exam.paper.ExamPaper;
import com.base.cn.platform.os.entity.exam.paper.ExamPaperCondition;
import com.base.cn.platform.os.entity.order.order.OrderDetails;
import com.base.cn.platform.os.entity.order.order.ShopCart;
import com.base.cn.platform.os.entity.order.shop.ShopData;
import com.base.cn.platform.os.entity.qa.question.QaQuestion;
import com.base.cn.platform.os.entity.qa.question.QuestionCondition;
import com.base.cn.platform.os.entity.user.member.CusUserMember;
import com.base.cn.platform.os.service.course.book.BookService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.course.qa.question.QaQuestionService;
import com.base.cn.platform.os.service.exam.paper.ExamPaperService;
import com.base.cn.platform.os.service.order.check.CreateOrderDataFrom;
import com.base.cn.platform.os.service.order.order.ShopCartBiz;
import com.base.cn.platform.os.service.user.member.CusUserMemberBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品数据初始化
 *
 * @author s.li
 * @date 2019/05/27
 */
@Component
public class ShopDataInit {
    @Autowired
    private CourseService courseService;
    @Autowired
    private BookService bookService;
    @Autowired
    private ExamPaperService examPaperService;
    @Autowired
    private CusUserMemberBiz cusUserMemberBiz;
    @Autowired
    private QaQuestionService qaQuestionService;
    @Autowired
    private ShopCartBiz shopCartBiz;

    /**
     * 初始化商品数据
     */
    public void initShopData(CreateOrderDataFrom createOrderDataFrom){
        String shopData = createOrderDataFrom.getShopData();
        List<ShopData> shopDataList = new ArrayList<>();
        if(StringUtils.isNotEmpty(shopData)){
            String[] arr = StringUtils.subHeadTailString(shopData,",").split(",");
            Arrays.stream(arr).forEach(em ->{
                if(StringUtils.isNotEmpty(em)){
                    String[] _arr = em.split("-");
                    ShopData shop = new ShopData();
                    shop.setShopId(new BigDecimal(_arr[0]));//商品ID
                    shop.setShopType(_arr[1]);//商品类型
                    if(ShopType.ORDER_SHOP_ACCOUNT.equals(shop.getShopType())){//如果是账户充值类型，则设置充值的金额
                        double price = Math.abs(Double.parseDouble(_arr[2]));//获取绝对值
                        shop.setOldPrice(price);
                        shop.setMemberPrice(price);
                        shop.setRealPrice(price);
                        shop.setBuyNum(1);
                    }else{//如果不是账户充值商品，设置购买量
                        shop.setBuyNum(Math.abs(Integer.parseInt(_arr[2])));//购买量 、获取绝对值
                    }
                    if(_arr.length>3){//如果有4个元素，证明有推广员KEY，第4个元素必须是推广员KEY
                        String shareKey = _arr[3];
                        if(StringUtils.isNotEmpty(shareKey)){
                            String _userId = shareKey.split("_")[1];
                            //如果推广员不是本身
                            if(createOrderDataFrom.getUserId().compareTo(new BigDecimal(_userId)) != 0){
                                shop.setShareKey(shareKey);//设置推广员KEY
                            }
                        }
                    }
                    shopDataList.add(shop);
                }
            });
        }else{
            List<ShopCart> shopCartList = shopCartBiz.findUserShopCartList(createOrderDataFrom.getUserId());
            if(ObjectUtils.isNotEmpty(shopCartList)){
                shopCartList.forEach(shopCart ->{
                    ShopData shop = new ShopData();
                    shop.setShopCartId(shopCart.getId());
                    shop.setShopId(shopCart.getShopId());//商品ID
                    shop.setShopType(shopCart.getShopType());//商品类型
                    shop.setShareKey(shopCart.getShareKey());//推广员KEY
                    shop.setBuyNum(shopCart.getBuyNum());//购买量
                    shopDataList.add(shop);
                });
            }
        }
        //设置商品数据
        this.setShopData(shopDataList);
        //给表单设置数据
        createOrderDataFrom.setShopList(shopDataList);
        //设置商品总数量
        createOrderDataFrom.setShopNum(shopDataList.stream().mapToInt(ShopData::getBuyNum).sum());

        if(createOrderDataFrom.getOrder() !=null){
            //订单流水数据
            List<OrderDetails> orderDetailsList = createOrderDataFrom.getOrder().getOrderDetailsList();
            if(ObjectUtils.isNotEmpty(orderDetailsList)){
                Map<String,ShopData> shopDataMap = shopDataList.stream().collect(Collectors.toMap(e->e.getShopType()+"-"+e.getShopId(),e->e));
                Map<String,OrderDetails> orderDetailsMap = orderDetailsList.stream().collect(Collectors.toMap(e->e.getShopType()+"-"+e.getShopId(),e->e));
                orderDetailsMap.forEach((k,v)->{
                    ShopData _shopData = shopDataMap.get(k);
                    if(_shopData !=null){
                        v.setShop(_shopData);
                    }
                });
            }
        }
    }

    /**
     * 初始化数据
     * @param shopList
     */
    public void setShopData(List<ShopData> shopList){
        if(ObjectUtils.isNotEmpty(shopList)){
            //通过商品类型分组
            Map<String,List<ShopData>> shopListMaps = shopList.stream().filter(e->StringUtils.isNotEmpty(e.getShopType())).collect(Collectors.groupingBy(e->e.getShopType()));
            //在设置商品价格的过程，realPrice和memberPrice两个价格已乘以商品数量，
            //因此后续的价格不需要再用这两个价格去乘以商数量了
            shopListMaps.forEach((k,v)->{
                if(k.equals(ShopType.ORDER_SHOP_COURSE)){
                    this.setCourse(v);
                }else if(k.equals(ShopType.ORDER_SHOP_EXAM)){
                    this.setExam(v);
                }else if(k.equals(ShopType.ORDER_SHOP_BOOK)){
                    this.setBook(v);
                }else if(k.equals(ShopType.ORDER_SHOP_MEMBER)){
                    this.setMember(v);
                }else if(k.equals(ShopType.ORDER_SHOP_QA) || k.equals(ShopType.ORDER_SHOP_ATTEND)){
                    this.setQa(v);
                }else if(k.equals(ShopType.ORDER_SHOP_ACCOUNT)){
                    this.setAccount(v);
                }
            });
        }
    }

    /**
     * 设置课程数据
     * @param courseShopList 课程商品
     */
    private void setCourse(List<ShopData> courseShopList){
        String courseIds = courseShopList.stream().map(e->e.getShopId().toString()).collect(Collectors.joining(","));
        CourseCondition condition = new CourseCondition();
        condition.setIds(courseIds);
        Map<BigDecimal, Course> courseMap = courseService.findCourseToMap(condition);
        if(ObjectUtils.isNotEmpty(courseMap)){
            courseShopList.forEach(shop->{
                Course course = courseMap.get(shop.getShopId());
                shop.setCourse(course);
                shop.setShopName(course.getCourseName());
                int allow =  course.getAllow();
                if(allow !=2){//如果课程不是可以分销的，那则把分销KEY设置null
                    shop.setShareKey(null);
                }
                shop.setOldPrice(course.getRealPrice());
                shop.setRealPrice(course.getRealPrice() * shop.getBuyNum());
                shop.setMemberPrice(course.getMemberPrice() * shop.getBuyNum());
            });
        }
    }

    /**
     * 设置试卷数据
     * @param examShopList 试卷商品数据列表
     */
    private void setExam(List<ShopData> examShopList){
        //得到试卷ID串
        String examIds = examShopList.stream().map(e->e.getShopId().toString()).collect(Collectors.joining(","));
        ExamPaperCondition condition = new ExamPaperCondition();
        condition.setIds(examIds);
        //查询试卷列表
        Map<BigDecimal, ExamPaper> examMaps = examPaperService.findExamPaperMap(condition);
        if(ObjectUtils.isNotEmpty(examMaps)){
            examShopList.forEach(e->{
                BigDecimal examId = e.getShopId();
                ExamPaper exam = examMaps.get(examId);
                if(ObjectUtils.isNotEmpty(exam)){
                    e.setExam(exam);//设置商品对象的试卷数据
                    e.setShopName(exam.getName());
                    e.setOldPrice(exam.getPrice());
                    e.setRealPrice(exam.getPrice() * e.getBuyNum());
                    e.setMemberPrice(exam.getMemberPrice() * e.getBuyNum());
                }
            });
        }
    }

    /**
     * 设置图书商品
     * @param bookShopList
     */
    private void setBook(List<ShopData> bookShopList){
        String bookIds = bookShopList.stream().map(e->e.getShopId().toString()).collect(Collectors.joining(","));
        BookCondition condition = new BookCondition();
        condition.setIds(bookIds);
        Map<BigDecimal, Book> bookMap = bookService.findBookMap(condition);
        if(ObjectUtils.isNotEmpty(bookMap)){
            bookShopList.forEach(e->{
                BigDecimal bookId = e.getShopId();
                Book book = bookMap.get(bookId);
                if(ObjectUtils.isNotEmpty(book)){
                    e.setBook(book);//设置商品对象的试卷数据
                    e.setShopName(book.getBookName());
                    e.setOldPrice(book.getRealPrice());
                    e.setRealPrice(book.getRealPrice() * e.getBuyNum());
                    e.setMemberPrice(book.getMemberPrice() * e.getBuyNum());
                }
            });
        }
    }

    /**
     * 设置会员商品
     * @param memberShopList
     */
    private void setMember(List<ShopData> memberShopList){
        String memberIds = memberShopList.stream().map(e->e.getShopId().toString()).collect(Collectors.joining(","));
        Map<BigDecimal, CusUserMember> cusUserMemberMap = cusUserMemberBiz.findUserMemberToMapByIds(memberIds);
        if(ObjectUtils.isNotEmpty(cusUserMemberMap)){
            memberShopList.forEach(e->{
                CusUserMember userMember = cusUserMemberMap.get(e.getShopId());
                if(ObjectUtils.isNotEmpty(userMember)){
                    e.setMember(userMember);
                    e.setShopName(userMember.getMemberName());
                    e.setOldPrice(userMember.getPrice());
                    e.setRealPrice(userMember.getPrice() * e.getBuyNum());
                    e.setMemberPrice(userMember.getPrice() * e.getBuyNum());
                }
            });
        }
    }

    /**
     * 设置问答商品
     * @param qaList
     */
    private void setQa(List<ShopData> qaList){
        String qaIds = qaList.stream().map(e->e.getShopId().toString()).collect(Collectors.joining(","));
        QuestionCondition condition = new QuestionCondition();
        condition.setIds(qaIds);
        condition.setNoStatusLimit(true);
        Map<BigDecimal, QaQuestion> qaQuestionMap = qaQuestionService.findQuestionToMap(condition);
        if(ObjectUtils.isNotEmpty(qaQuestionMap)){
            qaList.forEach(e->{
                QaQuestion qaQuestion =qaQuestionMap.get(e.getShopId());
                if(ObjectUtils.isNotEmpty(qaQuestion)){
                    e.setQa(qaQuestion);
                    if(e.getShopType().equals(ShopType.ORDER_SHOP_ATTEND)){
                        e.setOldPrice(1);
                        e.setRealPrice(1);
                        e.setMemberPrice(1);
                        e.setShopName(qaQuestion.getContext());
                    }else{
                        e.setOldPrice(qaQuestion.getPrice());
                        e.setRealPrice(qaQuestion.getPrice() * e.getBuyNum());
                        e.setMemberPrice(qaQuestion.getPrice() * e.getBuyNum());
                        e.setShopName(qaQuestion.getContext());
                    }


                }
            });
        }
    }

    /**
     * 设置充值商品数据
     * @param accountShopList
     */
    private void setAccount(List<ShopData> accountShopList){
        accountShopList.forEach(e->{
            Map<String,Double> accountMap = new HashMap<>();
            accountMap.put("realPrice",e.getRealPrice());
            e.setAccount(accountMap);
            e.setShopName("账户充值");
        });
    }
}
